package com.wangwei.character;

import com.wangwei.character.keyindexcount.Student;

/**
 * 键索引计数法
 */
public class KeyIndexCount {


    public static void test(){
        Student[] students =new Student[5];
        students[0] = new Student(1,"张三",1);
        students[1] = new Student(2,"李四",2);
        students[2] = new Student(3,"王五",3);
        students[3] = new Student(4,"赵六",1);
        students[4] = new Student(5,"阮小七",4);

        int N = students.length;
        int R =5;

        Student[] aux =new Student[N];
        int[] count = new int[R+1];

        //计算频率
        for(int i=0;i<N;i++){
            count[students[i].getGroup()+1]++;
        }

        //频率转索引  前面的小键相加
        /**
         * 频率转换为索引，目的是把每一阶段的第一个元素的缩影算出来。 使用过之后+1 ，以便让下一个索引使用。
         */
        for(int r =0;r < R;r++){
            count[r+1] += count[r];
        }


        //元素分类  划分按组别（键）
        for (int i = 0; i < N; i++) {
            /**
             * 分解的写法
             */
            int group = students[i].getGroup();//获得当前组
            int index =  count[group];//获得当前组的索引
            aux[index] = students[i];//赋值
            count[group]++;//索引++

            /**
             * 整合的写法
             */
//            aux[count[students[i].getGroup()]++] = students[i];
        }
        for (int i = 0; i < N; i++) {
            students[i] = aux[i];
        }

        for(int i =0;i< N;i++){
            System.out.println(" 姓名："+ students[i].getName() + " 组："+ students[i].getGroup());
        }
    }

    public static void main(String[] args) {
        test();
    }
}
